const path = require('path');
const Koa = require('koa');
const app = new Koa();
const cfg_app = require('./config').app;

// console-log 控制台输出访问的简单日志
cfg_app.app_debug && app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.status} ${ctx.url} - ${ms}ms`);
});

// static 静态文件
cfg_app.static_dir && app.use(require('koa-static')(
  path.join(path.dirname(module.parent.parent.filename), cfg_app.static_dir)
));

// koa-body 支持post的参数获取
cfg_app.koa_body && app.use(
  require('koa-body')(typeof cfg_app.koa_body === 'object' ?
    cfg_app.koa_body : {}
  )
);

// loader 加载器，封装zs对象
app.use(async (ctx, next) => {
  ctx.$zs = require('noader')(path.join(path.dirname(module.parent.parent.filename), './app'), ctx, next);
  ctx.$zs.config === undefined && (ctx.$zs.config = {});
  ctx.$zs.config.app = cfg_app;
  await next();
});

// router 路由
const router = require('./router');
app.use(router.routes());
app.use(router.allowedMethods());

// error 错误处理
app.on('error', (err, ctx) => {
  console.log('server error', err, ctx);
});

module.exports = app;
